#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h>

#define THRNUM  	4

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static int num;

static int next(int n)
{
	if(n + 1 == THRNUM)
		return 0;
	return n + 1;
}

// 需要定义在main上面，否则找不到，或者先声明
static void *calculate(void *p)
{
	int n = (int)p;
	int c = 'a' + n;

	while(1)
	{
		// 线程刚创建以后是拿不到锁的，需要外部释放第一把锁之后才拿到锁，当拿到锁以后，当前线程就被锁住
		pthread_mutex_lock(&mutex);
		while(num != n)
		{
			pthread_cond_wait(&cond, &mutex);
		}
		write(1,&c,1);
		num = next(num);
		pthread_cond_broadcast(&cond);
		// 锁住当前线程以后，释放下一把锁，然后第二个线程就可以获取到锁，然后以此类推。。。
		pthread_mutex_unlock(&mutex);
	}

    pthread_exit(NULL);
}
/*
 * 实现，4个线程顺序的向控制台输出abcd
 * */
int main(int argc, char **argv)
{
	int i, err;
	pthread_t tids[THRNUM];

	for (i = 0; i < THRNUM; ++i) {
		err = pthread_create(tids + i, NULL, calculate, (void *)i);
		if (err) {
            fprintf(stderr, "pthread_create(): %s\n", strerror(err));
            exit(1);
        }	
	}

	// 1s 后接收一个时钟信号来杀死进程
	alarm(1);

	// 线程一直在运行，不会走到收尸阶段
	for (i = 0; i < THRNUM; ++i) {
        pthread_join(tids[i], NULL);
    }

	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);

	exit(0);
}
